package com.egao.common.module.student.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.component.minio.config.MinioBucket;
import com.egao.common.component.minio.service.MinioService;
import com.egao.common.core.Constants;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.web.JsonResult;
import com.egao.common.core.web.PageParam;
import com.egao.common.core.web.PageResult;
import com.egao.common.module.student.constants.StudentConstants;
import com.egao.common.module.student.constants.StudentSignBlankConstants;
import com.egao.common.module.student.constants.StudentSignConstants;
import com.egao.common.module.student.entity.Student;
import com.egao.common.module.student.entity.StudentRecord;
import com.egao.common.module.student.entity.StudentSign;
import com.egao.common.module.student.entity.StudentSignBlank;
import com.egao.common.module.student.entity.print.DealPrintVO;
import com.egao.common.module.student.entity.vo.StudentFormVO;
import com.egao.common.module.student.entity.vo.StudentSignBlankListVO;
import com.egao.common.module.student.entity.vo.StudentTitleVO;
import com.egao.common.module.student.mapper.StudentSignBlankMapper;
import com.egao.common.module.student.service.StudentRecordService;
import com.egao.common.module.student.service.StudentService;
import com.egao.common.module.student.service.StudentSignBlankService;
import com.egao.common.module.student.service.StudentSignService;
import com.egao.common.module.system.constants.DictConstants;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.service.DictService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 学生签约空白协议接口实现
 * @author lym
 */
@Service
public class StudentSignBlankServiceImpl extends ServiceImpl<StudentSignBlankMapper, StudentSignBlank> implements StudentSignBlankService {

    @Autowired
    private StudentService studentService;
    @Autowired
    private StudentRecordService studentRecordService;
    @Autowired
    private DictService dictService;
    @Autowired
    private StudentSignService studentSignService;
    @Autowired
    private MinioService minioService;

    @Override
    public PageResult<StudentSignBlankListVO> listPage(PageParam<StudentSignBlankListVO> page) {
        String category = page.getString("category");
        category = !StrUtil.isBlank(category) ? category : "1";

        // 是学生 不带查询条件
        Integer studentId = page.getInt("studentId");
        if (null != studentId) {
            category = "0";
        }

        Integer checkState = null;
        Integer signState = null;
        if (StudentSignBlankConstants.CATEGORY_1.equals(category)) {
            checkState = 2;
        }
        if (StudentSignBlankConstants.CATEGORY_2.equals(category)) {
            checkState = 3;
        }
        if (StudentSignBlankConstants.CATEGORY_3.equals(category)) {
            checkState = 0;
            signState = 2;
        }
        if (StudentSignBlankConstants.CATEGORY_4.equals(category)) {
            signState = 0;
        }
        if (StudentSignBlankConstants.CATEGORY_5.equals(category)) {
            signState = 1;
        }
        if (StudentSignBlankConstants.CATEGORY_6.equals(category)) {
            checkState = 4;
        }

        page.put("checkState", checkState);
        page.put("signState", signState);
        List<StudentSignBlankListVO> list = baseMapper.listPage(page);

        for (StudentSignBlankListVO item : list) {
            String imgUrl = item.getImgUrl();
            String imgUrlPreview = minioService.getPreSignedObjectUrl(MinioBucket.MINIO_BLANK, imgUrl);
            item.setImgUrlPreview(imgUrlPreview);
        }

        return new PageResult<>(list, page.getTotal());
    }

    @Override
    public JsonResult detail(Integer id, Integer loginUserId, String collegeCode) {
        List<StudentTitleVO> students = studentService.listStudentTitle(collegeCode);

        StudentSignBlank studentSignBlank = new StudentSignBlank();

        // 新增表单
        if (null == id) {
            studentSignBlank.setCheckState(999);
            studentSignBlank.setCreateBy(loginUserId);
        } else {
            // 查看表单
            studentSignBlank = baseMapper.selectById(id);
            if (null == studentSignBlank) {
                throw new BusinessException("参数异常");
            }
            String imgUrlPreview = minioService.getPreSignedObjectUrl(MinioBucket.MINIO_BLANK, studentSignBlank.getImgUrl());
            studentSignBlank.setImgUrlPreview(imgUrlPreview);
        }

        return JsonResult.ok().setData(studentSignBlank).put("students", students);
    }

    @Override
    public JsonResult add(StudentSignBlank studentSignBlank, Integer loginUserId) {
        if (null == studentSignBlank) {
            throw new BusinessException("参数异常");
        }

        Student student = studentService.getById(studentSignBlank.getStudentId());
        if (null == student) {
            throw new BusinessException("学生参数异常");
        }

        JsonResult jsonResult = verify(studentSignBlank.getStudentId());
        if (Constants.RESULT_ERROR_CODE == jsonResult.getCode()) {
            return jsonResult;
        }

        studentSignBlank.setCheckState(StudentSignBlankConstants.CHECK_STATE_STUDENT_WAIT);
        studentSignBlank.setSignState(StudentSignBlankConstants.SIGN_STATE_WAIT);
        studentSignBlank.setCreateBy(loginUserId);

        if (baseMapper.insert(studentSignBlank) > 0) {
            // 添加一条记录
            studentRecordService.save(
                    new StudentRecord(loginUserId, student.getId(), StudentConstants.RECORD_TYPE_SIGN_BLANK, StudentConstants.RECORD_OPERATE_STUDENT_SIGN_BLANK_ADD)
            );

            return JsonResult.ok();
        }

        return JsonResult.error("操作异常，新增空白协议失败");
    }

    @Transactional
    @Override
    public JsonResult edit(StudentSignBlank studentSignBlank, Integer loginUserId) {
        StudentSignBlank update = baseMapper.selectById(studentSignBlank);
        if (null == update) {
            throw new BusinessException("数据异常");
        }
        update.setCheckState(studentSignBlank.getCheckState());
        update.setCheckContent(studentSignBlank.getCheckContent());
        update.setCheckUserId(loginUserId);

        Student student = studentService.getById(update.getStudentId());
        if (null == student) {
            throw new BusinessException("学生信息异常");
        }

        // 通过时
        if (StudentSignBlankConstants.CHECK_STATE_PASS.equals(update.getCheckState())) {
            // 验证一个学生只能有一个空白协议审核通过
            int count = baseMapper.selectCount(new QueryWrapper<StudentSignBlank>()
                    .eq("student_id", update.getStudentId())
                    .eq("check_state", StudentSignBlankConstants.CHECK_STATE_PASS)
                    .ne("id", update.getId())
            );
            if (count > 0) {
                throw new BusinessException("一个学生只能有一个空白协议审核通过");
            }

            // 验证当前学生没有毕业去向登记信息
            StudentSign studentSign = studentSignService.getStateValid(student.getUserId());
            if (null != studentSign) {
                throw new BusinessException("当前学生有正在进行的毕业去向信息登记，无法审核通过");
            }
        }

        // 作废时 重置对应的毕业去向登记
        if (StudentSignBlankConstants.CHECK_STATE_COLLEGE_FAIL.equals(update.getCheckState())) {
            StudentSign studentSign = studentSignService.getStateValid(student.getUserId());
            if (null != studentSign && update.getId().equals(studentSign.getBlankId())) {
                studentSignService.resetSignCategoryByBlank(studentSign, loginUserId);
            }
        }

        if (baseMapper.updateById(update) > 0) {

            // 添加一条记录
            studentRecordService.save(
                    new StudentRecord(loginUserId, update.getStudentId(), StudentConstants.RECORD_TYPE_SIGN_BLANK, StudentConstants.RECORD_OPERATE_STUDENT_SIGN_BLANK_EDIT, update.getCheckContent())
            );

            // 审核通过 给学生创建一个协议就业自主录入毕业去向登记信息
            if (StudentSignBlankConstants.CHECK_STATE_PASS.equals(update.getCheckState())) {
                student.setSignCategory(StudentSignConstants.SIGN_CATEGORY_XYJY);
                studentService.updateById(student);

                StudentSign studentSign = new StudentSign();
                studentSign.setBlankId(update.getId());
                studentSign.setUserId(student.getUserId());
                studentSign.setStudentId(student.getId());
                studentSign.setDealCompanyName(update.getCompanyName());
                studentSign.setState(StudentSignConstants.STATE_VALID);
                studentSign.setSignCategory(StudentSignConstants.SIGN_CATEGORY_XYJY);
                studentSign.setSignWay(StudentSignConstants.SIGN_WAY_STUDENT);
                studentSign.setDealCategory(StudentSignConstants.SIGN_DEAL_CATEGORY_FALSE);
                studentSign.setDealRolePick(StudentSignConstants.SIGN_DEAL_ROLE_PICK_STUDENT);
                studentSign.setDispatchHkAddressWho(StudentSignConstants.DISPATCH_HK_ADDRESS_WHO_STUDENT);
                studentSign.setSignState(StudentSignConstants.SIGN_STATE_STUDENT_WAIT);
                studentSign.setDispatchState(StudentSignConstants.DISPATCH_STATE_STUDENT_WAIT);
                studentSign.setDispatchJobCondition(StudentSignConstants.SIGN_JYZK_XYJY);
                studentSign.setDispatchJobCategory(StudentSignConstants.SIGN_CATEGORY_XYJY);
                studentSign.setSerialNumber(studentSignService.initSerialNumber());
                studentSignService.save(studentSign);

                studentRecordService.save(
                        new StudentRecord(loginUserId, student.getId(), StudentConstants.RECORD_TYPE_SIGN_BLANK, StudentConstants.RECORD_OPERATE_STUDENT_SIGN_BLANK_PICK)
                );
            }

            return JsonResult.ok();
        }

        return JsonResult.error("操作异常，修改空白协议失败");
    }

    @Override
    public JsonResult upload(StudentSignBlank studentSignBlank, Integer loginUserId) {
        if (null == studentSignBlank.getId()) {
            throw new BusinessException("参数异常");
        }

        StudentSignBlank insert = baseMapper.selectById(studentSignBlank);
        if (null == insert) {
            throw new BusinessException("数据异常");
        }
        insert.setImgUrl(studentSignBlank.getImgUrl());

        Student student = studentService.getById(insert.getStudentId());
        if (null == student) {
            throw new BusinessException("学生信息异常");
        }

        if (!loginUserId.equals(student.getUserId())) {
            throw new BusinessException("异常操作，信息不一致");
        }

        if (StrUtil.isBlank(insert.getImgUrl())) {
            throw new BusinessException("请上传打印表");
        }

        insert.setCheckState(StudentSignBlankConstants.CHECK_STATE_WAIT);
        if (baseMapper.updateById(insert) > 0) {
            // 添加一条记录
            studentRecordService.save(
                    new StudentRecord(loginUserId, insert.getStudentId(), StudentConstants.RECORD_TYPE_SIGN_BLANK, StudentConstants.RECORD_OPERATE_STUDENT_SIGN_BLANK_STUDENT_UPLOAD)
            );

            return JsonResult.ok();
        }

        return JsonResult.error("操作异常，上传打印表失败");
    }

    @Override
    public JsonResult verify(Integer studentId) {
        Student student = studentService.getById(studentId);
        if (null == student) {
            return JsonResult.error("学生信息异常");
        }

        List<StudentSignBlank> list = baseMapper.selectList(new QueryWrapper<StudentSignBlank>()
                .eq("student_id", studentId)
        );

        if (list == null || list.size() == 0) {
            return JsonResult.ok();
        }

        if (list.size() >= StudentSignBlankConstants.BLANK_COUNT) {
            return JsonResult.error("当前学生已有三个空白协议，无法再新增");
        }

        boolean b = true;
        for (StudentSignBlank blank : list) {
            if (!StudentSignBlankConstants.CHECK_STATE_COLLEGE_FAIL.equals(blank.getCheckState())) {
                b = false;
                break;
            }
        }

        if (b) {
            return JsonResult.ok();
        }

        StudentSign studentSign = studentSignService.getStateValid(student.getUserId());
        if (null != studentSign) {
            return JsonResult.error("当前学生有正在进行的毕业去向登记信息，无法新增空白协议");
        }

        return JsonResult.error("无法操作，该学生当前有空白协议正在进行中");
    }

    @Override
    public JsonResult verifySign(Integer studentId) {
        List<StudentSignBlank> list = baseMapper.selectList(new QueryWrapper<StudentSignBlank>()
                .eq("student_id", studentId)
        );

        if (list == null || list.size() == 0) {
            return JsonResult.ok();
        }

        boolean b = true;
        for (StudentSignBlank blank : list) {
            if (!StudentSignBlankConstants.CHECK_STATE_COLLEGE_FAIL.equals(blank.getCheckState())) {
                b = false;
                break;
            }
        }

        if (b) {
            return JsonResult.ok();
        }
        return JsonResult.error("无法操作，该学生当前有空白协议正在进行中");
    }

    @Override
    public JsonResult print(Integer id, Integer loginUserId) {
        if (null == id) {
            throw new BusinessException("参数异常");
        }

        StudentSignBlank studentSignBlank = baseMapper.selectById(id);
        if (null == studentSignBlank) {
            throw new BusinessException("数据异常");
        }

        if (null == studentSignBlank.getStudentId()) {
            throw new BusinessException("学生参数异常");
        }

        StudentFormVO student = studentService.getDetail(studentSignBlank.getStudentId());
        if (null == student) {
            throw new BusinessException("学生数据异常");
        }

        if (null != loginUserId) {
            if (!loginUserId.equals(student.getUserId())) {
                throw new BusinessException("异常数据");
            }
        }

        DealPrintVO dealPrintVO = new DealPrintVO();
        dealPrintVO.setId(id);
        dealPrintVO.setTitle("中南财经政法大学毕业生就业协议备案表(" + student.getYearId() + " 届 )");
        dealPrintVO.setDealSignCompanyName(studentSignBlank.getCompanyName());

        dealPrintVO.setXm(student.getXm());
        dealPrintVO.setXb(dictService.cacheLabel(DictConstants.TYPE_XB, student.getXb()));
        dealPrintVO.setZzmm(dictService.cacheLabel(DictConstants.TYPE_ZZMM, student.getZzmm()));
        dealPrintVO.setCollegeName(student.getCollegeName());
        dealPrintVO.setMajorName(student.getMajorName());
        dealPrintVO.setXh(student.getXh());
        dealPrintVO.setXl(dictService.cacheLabel(DictConstants.TYPE_XL, student.getXl()));
        dealPrintVO.setCsrq(student.getCsrq());
        dealPrintVO.setEmail(student.getEmail());
        dealPrintVO.setSyszd(dictService.cacheLabel(DictConstants.TYPE_SYSZD, student.getSyszd()));
        dealPrintVO.setMobile(student.getMobile());
        dealPrintVO.setJtdz(student.getJtdz());
        dealPrintVO.setJtyzbm(student.getJtyzbm());

        return JsonResult.ok().setData(dealPrintVO);
    }
}
